package com.nh.glory.admin.modular.system.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.nh.glory.core.R;
import com.nh.glory.core.util.Func;
import com.nh.glory.data.model.User;
import com.nh.glory.data.vo.UserVO;
import com.nh.glory.ware.service.system.DictService;
import com.nh.glory.ware.service.system.UserService;
import com.nh.glory.ware.support.Condition;
import com.nh.glory.ware.support.Query;
import com.nh.glory.ware.wrapper.UserWrapper;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 控制器
 *
 */
@RestController
@RequestMapping("/users")
@AllArgsConstructor
public class UserController {

    private UserService userService;

    private DictService dictService;

    /**
     * 查询单条
     */
    @GetMapping("{id}")
    public R<UserVO> detail(@PathVariable Long id) {
        User detail = userService.getById(id);
        UserWrapper userWrapper = new UserWrapper(userService, dictService);
        return R.ok(userWrapper.entityVO(detail));
    }

    /**
     * 用户列表
     */
    @GetMapping
    public R<IPage<UserVO>> list(@RequestParam Map<String, Object> user, Query query) {
        QueryWrapper<User> queryWrapper = Condition.getQueryWrapper(user, User.class);
        IPage<User> pages = userService.page(Condition.getPage(query), queryWrapper);
        UserWrapper userWrapper = new UserWrapper(userService, dictService);
        return R.ok(userWrapper.pageVO(pages));
    }

    /**
     * 新增或修改
     */
    @PostMapping
    public R submit(@Valid @RequestBody User user) {
        if(user.getId() == null) {
            if (user.getDeleted() == null) user.setDeleted(0);
            if(user.getCreateTime() == null) user.setCreateTime(new Date());
        }
        return R.status(userService.submit(user));
    }

    /**
     * 修改
     */
    @PostMapping("/update")
    public R update(@Valid @RequestBody User user) {
        return R.status(userService.updateById(user));
    }

    /**
     * 删除
     */
    @DeleteMapping
    public R remove(@RequestParam String ids) {
        List<Long> list = Func.toLongList(ids);
        if (list.contains(1L)) {
            return R.fail(400, "不能删除管理员");
        }
        return R.status(userService.removeByIds(list));
    }


    /**
     * 设置菜单权限
     *
     * @param userIds
     * @param roleIds
     * @return
     */
    @PostMapping("/grant")
    public R grant(@RequestParam String userIds, @RequestParam String roleIds) {
        boolean temp = userService.grant(userIds, roleIds);
        return R.status(temp);
    }

    @PostMapping("/reset-password")
    public R resetPassword(@RequestParam String userIds) {
        boolean temp = userService.resetPassword(userIds);
        return R.status(temp);
    }

}
